/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class PageUtil {

    private PageUtil() {
    }

    /**
     * Pages data with pageNo and pageSize
     *
     * @param data     all data that needs to be paged
     * @param pageNo   page number
     * @param pageSize each page size
     * @return page data
     */
    public static <T> List<T> pageData(List<T> data, int pageNo, int pageSize) {
        int startIndex = (pageNo - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, data.size());
        if (startIndex > endIndex) {
            return Collections.emptyList();
        }
        return data.stream().skip(startIndex).limit((long) endIndex - startIndex).collect(Collectors.toList());
    }

    /**
     * Pages data with pageNo and pageSize. This will return page info pojo
     *
     * @param data     all data that needs to be paged
     * @param pageNo   page number
     * @param pageSize each page size
     * @return page info
     */
    public static <T> Page<T> getPageData(List<T> data, int pageNo, int pageSize) {
        List<T> paginate = pageData(data, pageNo, pageSize);
        int totalItems = data.size();
        int totalPages = (int) Math.ceil((double) totalItems / pageSize);
        Page<T> pageInfo = new Page<>();
        pageInfo.setTotal(totalItems);
        pageInfo.setSize(pageSize);
        pageInfo.setPages(totalPages);
        pageInfo.setCurrent(pageNo);
        pageInfo.setRecords(paginate);
        return pageInfo;
    }


}
